package cc.chinagps.gateway.client.handler;

import cc.chinagps.gateway.client.*;
import cc.chinagps.gateway.client.bean.DeviceInfo;
import cc.chinagps.gateway.log.LogManager;
import io.netty.channel.*;

@ChannelHandler.Sharable
public class UnitClientReconnectHandler extends ChannelInboundHandlerAdapter {
    private UnitClient client;

    public UnitClientReconnectHandler(UnitClient client) {
        this.client = client;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        DeviceInfo deviceInfo = client.getDeviceInfo();
        LogManager.t("[{}] unitClient connected,localAddress:{},remoteAddress:{}", deviceInfo.getTerminalNo(), ctx.channel().localAddress().toString(), ctx.channel().remoteAddress().toString());
        client.initSession(ctx);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        DeviceInfo deviceInfo = client.getDeviceInfo();
        Channel ch = ctx.channel();
        LogManager.t("[{}] unitClient disconnected,localAddress:{},remoteAddress:{}", deviceInfo.getTerminalNo(), ch.localAddress().toString(), ch.remoteAddress().toString());
        client.reconnect(ctx);
        ctx.fireChannelInactive();
    }
}